# -*- coding: GBK -*-
import cv2 as cv
import numpy as np
import datetime

fn = "E:/Study/OpenCV/opencv/sources/samples/data/vtest.avi"

cap = cv.VideoCapture()
cap.open(fn)

_, src = cap.read()
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
pnt0 = cv.goodFeaturesToTrack(gray, 50, 0.01, 20)
pnt1 = pnt0
lastGray = gray
size = 50
while (True):
    _, src = cap.read()
    gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)

    if size<20:
        pnt0 = cv.goodFeaturesToTrack(gray, 50, 0.01, 20)

    cv.calcOpticalFlowPyrLK(lastGray, gray, pnt0, pnt1)
    cnt = 0
    for i in range(len(pnt1)):
        dist = cv.norm(pnt1[i] - pnt0[i])
        if dist >= 1.5 and dist <= 20.0:
            pnt0[cnt] = pnt0[i]
            pnt1[cnt] = pnt1[i]
            cnt += 1
    size = cnt
    rst = cv.resize(src,(0,0),fx=1,fy=1)

    for i in range(size):
        x0, y0 = pnt0[i][0].ravel()
        x1, y1 = pnt1[i][0].ravel()
        cv.line(rst, (x0,y0), (x1, y1), (0, 0, 255),2)
        cv.circle(rst, (x0, y0), 5, (0, 255, 0))
        cv.circle(rst, (x1, y1), 5, (255, 0, 0))
    pnt0 = pnt1
    lastGray = gray
    cv.imshow("Origin", src)
    cv.imshow("Result", rst)
    key = cv.waitKey(100)
    if key == 27:
        break

cap.release()
cv.destroyAllWindows()
